#pragma once

#include<iostream>
#include<string>
#include<fstream>
#include<unordered_map>//kv映射
#include<unistd.h>
#include"Log.hpp"

using namespace log_ns;

const static std::string sep=": ";//分隔符
// sad: 悲伤的
class Dict
{
private:
    void LoadDict(const std::string&path)
    {
        std::ifstream in(path);//从path打开文件
        if(!in.is_open())//如果打开失败
        {
            LOG(FATAL,"open %s failed!\n",path.c_str());
            exit(1);
        }
        std::string line;
        while(std::getline(in,line))
        {
            LOG(DEBUG,"load info: %s , success\n",line.c_str());
            if(line.empty()) continue;
            auto pos=line.find(sep);
            if(pos==std::string::npos) continue;

            //走到这说明找到了: 
            std::string key=line.substr(0,pos);
            if(key.empty()) continue;
            std::string value=line.substr(pos+sep.size());
            if(value.empty()) continue;

            _dict.insert(std::make_pair(key,value));//kv插入到_dict中

        }
        LOG(INFO,"load %s done\n",path.c_str());

        in.close();
    }    
public:
    Dict(const std::string&dict_path)
    : _dict_path(dict_path)//初始化路径
    {
        //构造的时候把dict.txt的内容加载到map::_dict里面
        LoadDict(_dict_path);
    }
    std::string Translate(std::string word)
    {
        if(word.empty()) return "None";
        auto iter=_dict.find(word);
        if(iter==_dict.end()) return "None";
        else return iter->second;
    }
    ~Dict()
    {}
private:
    std::unordered_map<std::string,std::string> _dict;//字典
    std::string _dict_path;//字典的对应的路径
};